//
//  SRAlbumListViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/3/31.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRAlbumListViewController.h"

#import "FZHomeConstants.h"
#import "FZHomeCourseModel.h"
#import "SRAlbumService.h"

#import "SRAlbumListCollectionViewCell.h"
#import <MJRefresh.h>
#import "FZTextInputViewController.h"

#import "FZMCCacheManager.h"
#import "SRCommonConstants.h"
#import "SRSpeakingDatabaseManager.h"

#import "SRBookUnitSelectListViewController.h"

@interface SRAlbumListViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (strong, nonatomic) UICollectionView          *collectionView;
@property (strong, nonatomic) NSMutableArray            *items;
@property (assign, nonatomic) NSInteger                 start;

@property (strong, nonatomic) UIButton *addButton;
@property (strong, nonatomic) UIButton *feedbackButton;

@end

@implementation SRAlbumListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
    self.title = self.gradeModel.grade;
    
    [self setupData];
    [self setupView];
    
    
    WEAKSELF
    self.loadingView.clickButtonBlock = ^(id sender) {
        [weakSelf queryListData:NO];
    };
    
    [self showLoadingViewWithCompletedBlock:nil];
    [self queryListData:NO];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}
#pragma mark - Setup


- (void)setupData {
    self.items = [NSMutableArray arrayWithCapacity:0];
    self.start = 0;
}

- (void)setupView {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    CGFloat edgeSpace = kFZHomeCollectionViewEdgeSpace;
    
    CGFloat cellWidth = floorf((SCREEN_WIDTH - edgeSpace * 4) / 3.f) - 1;
    CGFloat cellHeight = 155 / 105.f * cellWidth + 30;
    
    layout.itemSize = CGSizeMake(cellWidth, cellHeight);
    layout.minimumLineSpacing = edgeSpace;
    layout.minimumInteritemSpacing = edgeSpace;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(edgeSpace * 2, edgeSpace, edgeSpace, edgeSpace);
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    collectionView.alwaysBounceVertical = YES;
    [collectionView registerNib:[UINib nibWithNibName:kSRAlbumListCollectionViewCell bundle:nil] forCellWithReuseIdentifier:kSRAlbumListCollectionViewCell];
    
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.allowsMultipleSelection = YES;
    
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    self.collectionView.backgroundColor = css.color_2;
    
    WEAKSELF
    [self.collectionView addLegendHeaderWithRefreshingBlock:^{
        weakSelf.start = 0;
        [weakSelf queryListData:YES];
    }];
    
//    [self.collectionView addLegendFooterWithRefreshingBlock:^{
//        [weakSelf queryListData:NO];
//    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.bottom.equalTo(self.view);
    }];
    
    self.addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.addButton setBackgroundImage:[UIImage imageWithColor:css.color_7] forState:UIControlStateNormal];
    [self.addButton setBackgroundImage:[UIImage imageWithColor:css.colorOfSeperatorColor] forState:UIControlStateDisabled];

    [self.addButton setTitleColor:css.color_4 forState:UIControlStateNormal];
    self.addButton.titleLabel.font = css.fontOfH5;
    
    self.feedbackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.feedbackButton setTitleColor:css.color_4 forState:UIControlStateNormal];
    self.feedbackButton.titleLabel.font = css.fontOfH8;
    
    [self.view addSubview:self.addButton];
    [self.view addSubview:self.feedbackButton];
    
    [self.addButton setTitle:@"确认添加" forState:UIControlStateNormal];
    [self.feedbackButton setTitle:@"找不到教材，反馈给我们吧" forState:UIControlStateNormal];
    
    [self.addButton addTarget:self action:@selector(onAddButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.feedbackButton addTarget:self action:@selector(onFeedbackButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    if (self.isAddHomework) {
//        [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.leading.trailing.equalTo(self.view);
//            make.bottom.equalTo(self.view.mas_bottom);
//            make.height.mas_equalTo(50);
//        }];
//        
//        [self.feedbackButton mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.leading.trailing.equalTo(self.view);
//            make.bottom.equalTo(self.addButton.mas_top);
//            make.height.mas_equalTo(40);
//        }];
        
        self.addButton.hidden = YES;
        [self.feedbackButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom);
            make.height.mas_equalTo(40);
        }];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.top.equalTo(self.view);
            make.bottom.equalTo(self.view).offset(-40);
        }];
        
    } else {
        [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom);
            make.height.mas_equalTo(50);
        }];

        [self.feedbackButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(self.view);
            make.bottom.equalTo(self.addButton.mas_top);
            make.height.mas_equalTo(40);
        }];
        
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.top.equalTo(self.view);
            make.bottom.equalTo(self.view).offset(-90);
        }];
        
    }
    
    [self.addButton setEnabled:NO];
}

- (void)queryListData:(BOOL)isRefresh{
    WEAKSELF
    
    [SRAlbumService queryBooksWithGradeID:self.gradeModel.gradeID start:self.start successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf.collectionView.header endRefreshing];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            NSArray *addItems = responseDataObject;
            if ([addItems isKindOfClass:[NSArray class]]) {
                NSInteger itemCount = [addItems count];
                if (isRefresh) {
                    weakSelf.start = itemCount;
                    [weakSelf.items removeAllObjects];

                } else {
                    weakSelf.start += itemCount;
                }
                
                for (FZHomeCourseModel *item in addItems) {
                    item.gradeName = weakSelf.gradeModel.grade;
                }
                
                [weakSelf.items addObjectsFromArray:addItems];
               
                if ([weakSelf.items count] > 0) {
                    [weakSelf hideLoadingView];
                } else {
                    [weakSelf emptyLoadingViewWithTitle:nil];
                }
                [weakSelf.collectionView reloadData];
                
            } else {
                [weakSelf emptyLoadingViewWithTitle:nil];
            }
            
        } else {
            [weakSelf failedLoadingViewWithTitle:message];
        }
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf.collectionView.header endRefreshing];
        if ([weakSelf.items count] > 0) {
            [weakSelf hideLoadingView];
        } else {
            [weakSelf failedLoadingViewWithTitle:nil];
        }
        [weakSelf showHUDError];
    }];
}

#pragma mark - Event

- (void)onAddButtonAction:(id)sender {
    if (![SRLoginManager sharedManager].hasLogin) {
        [[SRLoginManager sharedManager] showLoginViewSinceController:self];
        return;
    }
    
    WEAKSELF
    NSArray *selectedIndexPaths = self.collectionView.indexPathsForSelectedItems;
    NSMutableString *addIDs = [[NSMutableString alloc] init];
    for (NSIndexPath *indexPath in selectedIndexPaths){
        FZHomeCourseModel *item = self.items[indexPath.item];
        [[FZMCCacheManager defaultManager] addBook:item];
        [[FZMCCacheManager defaultManager] startDownloadBook:item];
        
        [SRSpeakingDatabaseManager saveBookModel:item];
        
        [addIDs appendFormat:@"%@,",item.identifier ];
        
    }
    [[FZMCCacheManager defaultManager] saveBookInfoToFile];
    
    [SRAlbumService addBooksWithBookIDs:addIDs successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [weakSelf showHUDHintWithText:@"添加成功"];
        } else {
            [weakSelf showHUDHintWithText:message];
        }
    } failBlock:^(id responseObject, NSError *error) {
        
    }];
    
    UIViewController *destVC = nil;
    
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:NSClassFromString(@"SRMyBookListViewController")]) {
            destVC = vc;
            break;
        }
    }
    
    if (destVC) {
        [self.navigationController popToViewController:destVC animated:YES];
    } else {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:SRBookDidAddNotification object:nil];
}

- (void)onFeedbackButtonAction:(id)sender {
    FZTextInputViewController *vc = [[FZTextInputViewController alloc] init];
    vc.isFeedback = YES;
    vc.tipTitle = @"意见反馈";
    vc.placeholder = @"请输入你的宝贵建议，让我们改善变得完美";
    vc.maxInputTextCount = 400;
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)updateNextButtonTitle {
    NSArray *selectedItems = self.collectionView.indexPathsForSelectedItems;
    
    if (selectedItems && [selectedItems count] > 0) {
        [self.addButton setEnabled:YES];
        NSString *title = [NSString stringWithFormat:@"确认添加（%lu）", [selectedItems count]];
        [self.addButton setTitle:title forState:UIControlStateNormal];

    } else {
        [self.addButton setEnabled:NO];
        NSString *title = [NSString stringWithFormat:@"确认添加"];
        [self.addButton setTitle:title forState:UIControlStateNormal];
    }
}

#pragma mark - UICollection DataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.items count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SRAlbumListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kSRAlbumListCollectionViewCell forIndexPath:indexPath];
    if (indexPath.item > [self.items count]) {
        return cell;
    }
    FZHomeCourseModel *item = self.items[indexPath.item];
    cell.checkButtonHidden = NO;
    cell.checkButtonStatus = item.isSelected;
    
    [cell updateCellInfo:item];
    
    return cell;
}

#pragma mark - UICollectionViewDelegate


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    FZHomeCourseModel *item = self.items[indexPath.item];
    if (self.isAddHomework) {
        SRBookUnitSelectListViewController *vc = [[SRBookUnitSelectListViewController alloc] init];
        vc.bookID = item.identifier;
        vc.groupID = self.groupID;
        
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    if ([[FZMCCacheManager defaultManager] isExistBook:item]) {
        [self showHUDHintWithText:@"该课本已经添加"];
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    } else {
        [self updateNextButtonTitle];
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self updateNextButtonTitle];
}

@end
